<template>
  <div>
    <v-form v-model="valid" ref="myBrandForm">

      <v-text-field v-model="brand.name" label="请输入品牌名称" :rules="nameRules"  required></v-text-field><br/>
      <v-text-field v-model="brand.letter" label="请输入品牌首字母" :rules="letterRules"  required></v-text-field><br/>
      <v-cascader
        url="/item/category/list"
        multiple
        required
        v-model="brand.categories"
        label="请选择商品分类"/>
      <v-layout row>
        <v-flex xs3>
          <span style="font-size: 16px; color: #444">品牌LOGO：</span>
        </v-flex>
        <v-flex>
          <v-upload
            v-model="brand.image"
            url="/upload/image"
            :multiple="false"
            :pic-width="250"
            :pic-height="90"
          />
        </v-flex>
      </v-layout>

      <v-layout class="my-4" row>
        <v-spacer/>
        <v-flex><v-btn color="primary" @click="submit">提交</v-btn></v-flex>
        <v-flex><v-btn color="pink" @click="clear">重置</v-btn></v-flex>
      </v-layout>
    </v-form>
  </div>
</template>

<script>
    export default {
        name: "my-brand-form",
      data() {
        return {
          valid:false, // 表单校验结果标记
          brand:{
            name:'', // 品牌名称
            letter:'', // 品牌首字母
            image:'',// 品牌logo
            categories:[], // 品牌所属的商品分类数组
          },
          nameRules: [
            v => !!v || '名称必须输入',
            v => v.length > 1 || '名字至少输入两个'
          ],
          letterRules:[
            v => !!v || "首字母不能为空",
            v => /^[A-Z]{1}$/.test(v) || "品牌字母只能是A~Z的大写字母"
          ]
        }
      },
      methods:{
          submit(){
            //判断表单是否通过验证
            if(this.$refs.myBrandForm.validate()){


                //提交数据
                let {categories,...params} = this.brand;


              //params为请求参数集合
              params.cids = categories.map(c => c.id).join(",");//4,76

              this.$http.post("/item/brand",this.$qs.stringify(params))
                .then(()=>{
                  this.$message.info("保存成功")
                  this.$emit("close");
                })
                .catch(()=>{
                  this.$message.error("保存失败");
                });
            }
          },
        clear(){
            //vue对象访问自己所有关联的对象，然后使用关联的对象的具体处理方法来做具体的操作
            this.$refs.myBrandForm.reset();
            //防止自定义组件中的值没有清空
            this.brand.categories=[]
        }
      }
    }
</script>

<style scoped>

</style>
